package util

import (
	"bytes"
	"encoding/json"
	"io"
	"log/slog"
	"net/http"
)

func CreateMemberSiteJsonRequest(url string, authHeader string, authAppId string, authSecret string, obj any) (*http.Request, error) {
	body, err := json.Marshal(obj)
	if err != nil {
		slog.Error("Json marshal", "err", err)
		return nil, err
	}
	auth, err := CreateClientAuthorization(authAppId, authSecret, body)
	if err != nil {
		slog.Error("Create client authorization", "err", err)
		return nil, err
	}
	httpReq, err := http.NewRequest("POST", url, bytes.NewReader(body))
	if err != nil {
		slog.Error("Create request", "err", err)
		return nil, err
	}
	httpReq.Header.Add("Content-Type", "application/json")
	httpReq.Header.Add(authHeader, auth)
	return httpReq, nil
}

func CreateMemberSiteGetRequest(url string, authHeader string, authAppId string, authSecret string) (*http.Request, error) {
	auth, err := CreateClientAuthorization(authAppId, authSecret, []byte{})
	if err != nil {
		slog.Error("Create client authorization", "err", err)
		return nil, err
	}
	if err != nil {
		slog.Error("Create client authorization", "err", err)
		return nil, err
	}
	httpReq, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}
	httpReq.Header.Add(authHeader, auth)
	return httpReq, nil
}

func LogHttpResponse(resp *http.Response) {
	slog.Info("Response Headers:")
	for hk, hv := range resp.Header {
		slog.Info("", hk, hv)
	}
	respBodyBs, _ := io.ReadAll(resp.Body)
	slog.Info("Response Body:")
	slog.Info(string(respBodyBs))
}
